package com.woyou.ui.fragment;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import retrofit.RetrofitError;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.citaq.ideliver.R;
import com.squareup.picasso.Picasso;
import com.woyou.bean.CodeResult;
import com.woyou.bean.Result;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.PhonePwdReq;
import com.woyou.bean.rpc.PwdCheckReq;
import com.woyou.service.LocationLoopService;
import com.woyou.service.NetWorkCenter;
import com.woyou.ui.activity.CollectionActivity_;
import com.woyou.ui.activity.FeedBackActivity_;
import com.woyou.ui.activity.LoginActivity_;
import com.woyou.ui.activity.MyAboutActivity_;
import com.woyou.ui.activity.MyAddrActivity_;
import com.woyou.ui.activity.MyCouPonActivity_;
import com.woyou.ui.activity.MyInfoActivity_;
import com.woyou.ui.activity.MySetUpActivity_;
import com.woyou.ui.activity.orderlist.MyOrderActivity;
import com.woyou.utils.Dialog;
import com.woyou.utils.InstallUtils;
import com.woyou.utils.LogUtil;
import com.woyou.utils.eventbus.EventHideUpdate;
import com.woyou.utils.eventbus.EventInfoSetup;
import com.woyou.utils.eventbus.EventShowBar;

import de.greenrobot.event.EventBus;

/**
 * 我的
 * 
 * @author tanglc
 */
@EFragment(R.layout.fm_my)
public class MyFragment extends SuperFragment {

	private static final String TAG = "MyFragment";

	private Dialog dialog = new Dialog();
	private UserInfo userInfo;

	Result<UserInfo> result;
	PwdCheckReq pwdCheckReq = new PwdCheckReq();

	@ViewById
	// 判断是否登录LoginFragment
	RelativeLayout fm_my_userinfo;
	@ViewById
	// 设置界面
	LinearLayout fm_my_setbtn, fm_about_feedbackbtn;
	@ViewById
	// 头像图标
	ImageView fm_my_userpic;

	@ViewById
	// 我的优惠券、我的积分、我的钱包
	LinearLayout fm_my_couponbtn, fm_my_integralbtn, fm_my_walletbtn,
			fm_my_about, rl, fm_my_collectionbtn, fm_my_addrbtn,
			fm_my_orderbtn, callphone;

	@ViewById
	// 用户姓名、我的优惠券、我的积分、我的钱包、我的订单、我的地址、我的收藏、我的消息、我的评论、定时提醒
	TextView fm_my_username, fm_my_coupontext, fm_my_integraltext,
			fm_my_wallettext, fm_my_messagebtn, fm_my_commentsbtn,
			fm_my_timepromptbtn, callphonetext, zhang;

	@Click({ R.id.fm_my_userinfo, R.id.fm_my_userpic, R.id.fm_my_couponbtn,
			R.id.fm_my_integralbtn, R.id.fm_my_walletbtn, R.id.fm_my_orderbtn,
			R.id.fm_my_addrbtn, R.id.fm_my_collectionbtn,
			R.id.fm_my_messagebtn, R.id.fm_my_commentsbtn,
			R.id.fm_my_timepromptbtn, R.id.fm_my_setbtn,
			R.id.fm_about_feedbackbtn, R.id.fm_my_about, R.id.callphone })
	void ClickBtn(View view) {
		switch (view.getId()) {
		case R.id.fm_my_setbtn:
			// 进入设置界面
			openActivity(MySetUpActivity_.class, null);
			break;

		case R.id.fm_my_userinfo:
		case R.id.fm_my_userpic:
			// Y 账户信息界面
			if (userInfo.getuId() != null && !userInfo.getuId().equals("")) {
				openActivity(MyInfoActivity_.class, null);
			} else {
				openActivity(LoginActivity_.class, null);
			}
			break;

		case R.id.fm_my_couponbtn: 
			// 我的优惠券
			couponPwdCheck();
			break;

		case R.id.fm_my_integralbtn:
			// 我的积分
			openActivity(LoginActivity_.class, null);
			break;

		case R.id.fm_my_walletbtn:
			// 我的钱包
			openActivity(LoginActivity_.class, null);
			break;

		case R.id.fm_my_orderbtn:
			// 我的订单
			if (!TextUtils.isEmpty(userInfo.getuId())) {
				openActivity(MyOrderActivity.class, null);
			} else {
				openActivity(LoginActivity_.class, null);
			}
			break;

		case R.id.fm_my_addrbtn:
			// 我的地址
			if (!TextUtils.isEmpty(userInfo.getuId())) {
				openActivity(MyAddrActivity_.class, null);
			} else {
				openActivity(LoginActivity_.class, null);
			}
			break;

		case R.id.fm_my_collectionbtn:
			// 我的收藏
			collectionPwdCheck();
			break;

		case R.id.fm_my_messagebtn:
			// 我的消息
			openActivity(LoginActivity_.class, null);
			break;

		case R.id.fm_my_commentsbtn:
			// 我的评论
			openActivity(LoginActivity_.class, null);
			break;

		case R.id.fm_my_timepromptbtn:
			// 定时提醒
			openActivity(LoginActivity_.class, null);
			break;

		case R.id.callphone:
			// 拨打客服电话
			Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+ callphonetext.getText().toString()));
			if(InstallUtils.isIntentAvailable(mContext, intent)){
				mContext.startActivity(intent);
			}
			break;

		case R.id.fm_about_feedbackbtn:
			// 意见反馈
			openActivity(FeedBackActivity_.class, null);
			break;

		case R.id.fm_my_about:
			// 关于我们
			openActivity(MyAboutActivity_.class, null);
			break;

		default:
			break;
		}
	}

	/**
	 * 优惠券验证密码
	 */
	@SuppressWarnings("rawtypes")
	@Background
	void couponPwdCheck() {
		if (!NetWorkCenter.isNetworkConnected(getActivity())) {
			readCacheInfo();
			showToast("网络根本没连,赶紧检查");
			return;
		}
		if (TextUtils.isEmpty(userInfo.getuId())) {
			openActivity(LoginActivity_.class, null);
			return;
		}

		pwdCheckReq.setuId(userInfo.getuId());
		pwdCheckReq.setPwd(userInfo.getPwd());

		try {
			CodeResult result = mUserModel.pwdCheck(pwdCheckReq);
			if (result != null && result.getCode() == -3) {
				runOnUi(new Runnable() {

					@Override
					public void run() {
						dialog.LoginToast(mContext, "您的手机号已在别处登录,请重新登录");
					}
				});
			} else if (result != null && result.getCode() == 1) {
				if (!TextUtils.isEmpty(userInfo.getuId())) {
					openActivity(MyCouPonActivity_.class, null);
				} else {
					openActivity(LoginActivity_.class, null);
				}
			} else if (result != null && result.getCode() == -2) {
				showToast(result.msg);
			}
		} catch (RetrofitError e) {
			switch (e.getKind()) {
			case HTTP:
				showToast("很遗憾，网络不给力！");
				return;
			case CONVERSION:
				showToast("很抱歉，服务器又任性了！");
				return;
			case NETWORK:
				showToast("很遗憾，网络不给力！");
				return;
			case UNEXPECTED:
				showToast("很抱歉，服务器又任性了！");
				return;
			}
		}

	}

	/**
	 * 我的收藏验证密码
	 */
	@SuppressWarnings("rawtypes")
	@Background
	void collectionPwdCheck() {
		if (!NetWorkCenter.isNetworkConnected(getActivity())) {
			readCacheInfo();
			showToast("网络根本没连,赶紧检查");
			return;
		}
		if (TextUtils.isEmpty(userInfo.getuId())) {
			openActivity(LoginActivity_.class, null);
			return;
		}
		pwdCheckReq.setuId(userInfo.getuId());
		pwdCheckReq.setPwd(userInfo.getPwd());
		try {
			CodeResult result = mUserModel.pwdCheck(pwdCheckReq);
			if (result != null && result.getCode() == -1) {
				runOnUi(new Runnable() {

					@Override
					public void run() {
						dialog.LoginToast(mContext, "您的手机号已在别处登录,请重新登录");
					}
				});
			} else if (result != null && result.getCode() == 1) {
				if (!TextUtils.isEmpty(userInfo.getuId())) {
					openActivity(CollectionActivity_.class, null);
				} else {
					openActivity(LoginActivity_.class, null);
				}
			} else if (result != null && result.getCode() == -2) {
				showToast(result.msg);
			}
		} catch (RetrofitError e) {
			switch (e.getKind()) {
			case HTTP:
				showToast("很遗憾，网络不给力！");
				return;
			case CONVERSION:
				showToast("很抱歉，服务器又任性了！");
				return;
			case NETWORK:
				showToast("很遗憾，网络不给力！");
				return;
			case UNEXPECTED:
				showToast("很抱歉，服务器又任性了！");
				return;
			}
		}
	}

	@AfterViews
	public void initView() {
		EventBus.getDefault().register(this);
		// 初始化界面显示数据
		// queryUserInfo();
	}

	@Override
	public void onResume() {
		super.onResume();
		userInfo = mUserModel.getUserInfo();
		queryUserInfo();
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		userInfo = mUserModel.getUserInfo();
		if (!hidden) {
			queryUserInfo();
			EventBus.getDefault().post(new EventShowBar(3));
			Log.d(TAG, "onHiddenChanged:false");
		} else {
			EventBus.getDefault().post(new EventHideUpdate(3));
			Log.d(TAG, "onHiddenChanged:true");
		}
	}

	@Background
	void queryUserInfo() {
		if (!NetWorkCenter.isNetworkConnected(getActivity())) {
			readCacheInfo();
			showToast("网络根本没连,赶紧检查");
			return;
		}
		try {
			PhonePwdReq phonePwdReq = new PhonePwdReq();
			if (LocationLoopService.getInstance(mContext).getChosenAddr() != null) {
				phonePwdReq.setLat(LocationLoopService.getInstance(mContext)
						.getChosenAddr().getLat());
				phonePwdReq.setLng(LocationLoopService.getInstance(mContext)
						.getChosenAddr().getLng());
			} else {
				if (mBaiduLocationService.getLastLocation() != null) {
					phonePwdReq.setLat(mBaiduLocationService.getLastLocation()
							.getLatitude() + "");
					phonePwdReq.setLng(mBaiduLocationService.getLastLocation()
							.getLongitude() + "");
				} else {
					phonePwdReq.setLat("");
					phonePwdReq.setLng("");
				}
			}
			userInfo = mUserModel.getCompatibleUserInfo();
			if (!TextUtils.isEmpty(userInfo.getuId())) {
				phonePwdReq.setuId(userInfo.getuId());
				phonePwdReq.setPwd(userInfo.getPwd());
				// 设置用户名
				runOnUi(new Runnable() {
					@Override
					public void run() {
						if (userInfo.getName() != null
								&& !userInfo.getName().equals("")) {
							fm_my_username.setText(userInfo.getName());
						} else {
							fm_my_username.setText(userInfo.getuId());
						}
						if (!TextUtils.isEmpty(userInfo.getPicUrl())) {
							refreshIMG(userInfo.getPicUrl());
						} else {
							fm_my_userpic.setImageResource(R.raw.touxiang2);
						}
					}
				});
				result = mUserModel.v2_1queryUserInfo(phonePwdReq);
				LogUtil.i("phonePwdReq", phonePwdReq.toString());
				showView(result);
			} else {
				showDefaultInfo();
			}
		} catch (RetrofitError e) {
			switch (e.getKind()) {
			case HTTP:
				showToast("很遗憾，网络不给力！");
				return;
			case CONVERSION:
				showToast("很抱歉，服务器又任性了！");
				return;
			case NETWORK:
				showToast("很遗憾，网络不给力！");
				return;
			case UNEXPECTED:
				showToast("很抱歉，服务器又任性了！");
				return;
			}
		}
	}

	@UiThread
	void showView(Result<UserInfo> result) {
		if (result == null)
			return;
		UserInfo userInfo = result.getData();
		if (result.code == 1) {
			if (userInfo.getPicUrl() != null
					&& !userInfo.getPicUrl().equals("")) {
				refreshIMG(userInfo.getPicUrl());
			} else {
				fm_my_userpic.setImageResource(R.raw.touxiang2);
			}

			if (userInfo.getName() != null && !userInfo.getName().equals("")) {
				fm_my_username.setText(userInfo.getName());
			} else if (userInfo.getuId() != null
					&& !userInfo.getuId().equals("")) {
				fm_my_username.setText(userInfo.getuId());
			} else {
				fm_my_username.setText("快捷登录");
			}

			if (userInfo.getuId() != null && !userInfo.getuId().equals("")) {
				fm_my_coupontext.setText(String.valueOf(userInfo.getCoupon()));
				zhang.setText("张");
			} else {
				fm_my_coupontext.setText("");
				zhang.setText("");
			}
			fm_my_integraltext.setText(String.valueOf(userInfo.getIntegral())
					+ "积分");
			fm_my_wallettext
					.setText(String.valueOf(userInfo.getWallet()) + "元");

		} else if (result != null && result.code == -3) {
			dialog.LoginToast(mContext, result.getMsg());

		} else {
			showToast(result.msg);
		}
	}

	public void onEvent(EventInfoSetup event) {
		showProgressDialog();
		userInfo = mUserModel.getUserInfo();
		if (!TextUtils.isEmpty(userInfo.getPicUrl())) {
			refreshIMG(userInfo.getPicUrl());
		} else {
			fm_my_userpic.setImageResource(R.raw.touxiang2);
		}
		if (userInfo.getName() != null && !userInfo.getName().equals("")) {
			fm_my_username.setText(userInfo.getName());
		} else if (userInfo.getuId() != null && !userInfo.getuId().equals("")) {
			fm_my_username.setText(userInfo.getuId());
		} else {
			fm_my_username.setText("快捷登录");
		}
		if (userInfo.getuId() != null && !userInfo.getuId().equals("")) {
			fm_my_coupontext.setText(String.valueOf(userInfo.getCoupon()));
			zhang.setText("张");
		} else {
			fm_my_coupontext.setText("");
			zhang.setText("");
		}
		fm_my_integraltext.setText(String.valueOf(userInfo.getIntegral())
				+ "积分");
		fm_my_wallettext.setText(String.valueOf(userInfo.getWallet()) + "元");

		dismissProgressDialog();
	}

	/**
	 * 刷新我的汇总页面头像图标 tanglc
	 * 
	 * @param url
	 */
	private void refreshIMG(String url) {
		Picasso.with(mContext).load(url).into(fm_my_userpic);
	}

	Bitmap img = null;

	// 加载图片
	@Background
	void getUrlImage(String url) {
		try {
			URL picurl = new URL(url);
			// 获得连接
			HttpURLConnection conn = (HttpURLConnection) picurl
					.openConnection();
			conn.setConnectTimeout(6000);// 设置超时
			conn.setDoInput(true);
			conn.setUseCaches(false);// 不缓存
			conn.connect();
			InputStream is = conn.getInputStream();// 获得图片的数据流
			img = BitmapFactory.decodeStream(is);
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 显示Dialog的method
	 */
	@UiThread
	void showDialog(final String mess) {
		dialog.Toast(mActivity, mess);// 有问题
	}

	/**
	 * 显示默认信息
	 */
	@UiThread
	void showDefaultInfo() {
		if (userInfo.getName() != null && !userInfo.getName().equals("")) {
			fm_my_username.setText(userInfo.getName());
		} else if (userInfo.getuId() != null && !userInfo.getuId().equals("")) {
			fm_my_username.setText(userInfo.getuId());
		} else {
			fm_my_username.setText("快捷登录");
		}
		fm_my_userpic.setImageResource(R.raw.touxiang2);
		fm_my_coupontext.setText("");
		zhang.setText("");
	}

	/**
	 * 显示缓存中的个人信息
	 */
	@UiThread
	void readCacheInfo() {
		if (userInfo != null) {
			if (userInfo.getName() != null && !userInfo.getName().equals("")) {
				fm_my_username.setText(userInfo.getName());
			} else if (userInfo.getuId() != null
					&& !userInfo.getuId().equals("")) {
				fm_my_username.setText(userInfo.getuId());
			} else {
				fm_my_username.setText("快捷登录");
			}
			if (!TextUtils.isEmpty(userInfo.getPicUrl())) {
				refreshIMG(userInfo.getPicUrl());
			} else {
				fm_my_userpic.setImageResource(R.raw.touxiang2);
			}
			fm_my_coupontext.setText("");
			zhang.setText("");
		}
	}

	@Override
	public void retry() {
		// TODO Auto-generated method stub
	}

	@Override
	public void pwdError() {
		// TODO Auto-generated method stub
	}

	@Override
	public void netError() {
		// TODO Auto-generated method stub
	}

	@Override
	protected void obtainInfo() {
		// TODO Auto-generated method stub
	}

}
